using System;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;

namespace AvatarExample
{
    public class AvatarFetcher
    {
        public static Image GetAvatarFromDatabase(string connectionString, int userId)
        {
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                string query = "SELECT Avatar FROM Users WHERE Id = @UserId";
                SqlCommand command = new SqlCommand(query, connection);
                command.Parameters.AddWithValue("@UserId", userId);

                try
                {
                    connection.Open();
                    byte[] imageData = (byte[])command.ExecuteScalar();
                    if (imageData != null)
                    {
                        using (MemoryStream ms = new MemoryStream(imageData))
                        {
                            return Image.FromStream(ms);
                        }
                    }
                    return null;
                }
                catch (Exception ex)
                {
                    Console.WriteLine("获取头像时出错: " + ex.Message);
                    return null;
                }
            }
        }
    }
}